const jsonServer = require('json-server')
const server = jsonServer.create()
const middlewares = jsonServer.defaults()

const fake = require('faker')

server.use(middlewares)

server.use(jsonServer.rewriter({
	"/api/v1/wifi/*": "/$1"
}))

server.get('/echo', (req, res) => {
	res.jsonp(req.query)
})

server.get('/scaninfo', ({res}) => {
	let aplist=[]
	for (let i = 0; i < 7; i++) {
		aplist.push({
		ssid: fake.internet.userName(), 
		rssi: Math.round(Math.random()*-90),
		pwd: !!Math.round(Math.random()+0.2)})
	}
	res.jsonp(aplist)
})

// To handle POST, PUT and PATCH you need to use a body-parser
// You can use the one used by JSON Server
server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
	if (req.method === 'POST' && req.url === '/connect') {
		// req.body.createdAt = Date.now()
		let connect_res = {}
		if(!!Math.round(Math.random()+0.1)){
			connect_res={
				code:-1,
				str:"Connect ERROR"
			}
		}else{
			connect_res={
				code:101,
				str:"Connecting"
			}
		}	
		res.jsonp(connect_res)
	}
	// Continue to JSON Server router
	next()
})

server.listen(3000, () => {
	console.log('JSON Server is running')
})
